#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <bitset>
#include <utility>
using namespace std;

#define mm(a, n) memset(a, n, sizeof a)
#define mk(a, b) make_pair(a, b)

const double eps = 1e-6;
const int INF = 0x3f3f3f3f;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef pair<LL, LL> PLL;
typedef pair<int, LL> PIL;

inline void quickread() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
}

int k_[4][4], k[4][4];
int n[55][55];
int C[55][55];
int T, pos;

inline void solution() {
    cin >> T;
    while (T -- ) {
        cin >> pos;
        mm(C, 0);
        int sum = 0;
        for (int i = 1; i <= pos; i ++ ) 
            for (int j = 1; j <= pos; j ++ ) 
                cin >> n[i][j];
        
        for (int i = 1; i <= 3; i ++ ) 
            for (int j = 1; j <= 3; j ++ ) {
                cin >> k_[i][j];
                sum += k_[i][j];
            }

        // calc matrix K
        for (int i = 1; i <= 3; i ++ ) {
            for (int j = 1; j <= 3; j ++ ) {
                k[i][j] = k_[i][j] / (sum * 1.0);
                cout << k[i][j] << " ";
            }
            cout << endl;
        }

        // calc matrix C
        for (int x = 1; x <= pos; x ++ ) 
            for (int y = 1; y <= pos; y ++ ) 
                for (int i = 1; i <= min(pos - x + 1, 3); i ++ ) 
                    for (int j = 1; j <= min(pos - y + 1, 3); j ++ ) 
                        C[x][y] += n[x + i - 1][y + j - 1] * k[i][j];
        
        for (int i = 1; i <= pos; i ++ ) {
            for (int j = 1; j <= pos; j ++ ) {
                if (j == 1) 
                    cout << C[i][j];
                else
                    cout << " " << C[i][j];
            }
            cout << endl;
        }
    }
}

int main() {
    freopen("input.txt", "r", stdin);
    quickread();
    solution();
    return 0;
}